SELECT order_id, first_name, last_name FROM orders o INNERJOIN customers c ON o.customer_id = c.customer_id
注意: 内连接时,INNER 可不写。
如果连接的表中存在同名字段,我们就必须在 SELECT 子句中的该字段前指明表名前缀,否则会报错 ‘customer_id’ in field list is ambiguous:
SELECT order_id, o.customer_id, first_name, last_name FROM orders o INNERJOIN customers c ON o.customer_id = c.customer_id
注意: 如果跨数据库进行连接,则需要在表名前指定数据库前缀。
Self Join
我们也可以将一张表与其自身进行连接:
SELECT e.employee_id, e.first_name, m.first_name AS manager_name FROM employees e JOIN employees m ON e.reports_to = m.employee_id
Join Multiple Tables
SELECT order_id, order_date, first_name, last_name, `name` AS status FROM orders o JOIN customers c ON o.customer_id = c.customer_id JOIN order_statuses os ON os.order_status_id = o.`status`
Compound Join Conditions
我们在实际生产环境也常常遇见复合主键,复合主键的连接语句如下:
SELECT* FROM order_items oi JOIN order_item_notes oin ON oi.order_id = oin.order_id AND oi.product_id = oin.product_id